<template>
  <el-dialog
      title="图片库"
      v-model="open"
      width="750px"
      :close-on-click-modal="false"
      draggable
      :show-close="false"
  >
    <el-row>
      <el-col :span="5" style="text-align: center">
        <div class="menu-box" v-loading="loadingMenu">
          <div class="menu-title">图片分类</div>
          <el-scrollbar height="300px" style="margin: 20px 0">
            <div v-for="(item,index) in menuList" :key="item.name" @click="menuItemEvent(item,index)" class="menu-item" :class="menuIndex==index?'menu-active':''">
              <div class="menu-name">{{item.name}}</div>
              <el-icon  @click.stop="showMenuEdit(item,index)" v-if="item.sort!=-9999" class="menu-icon" color="#409eff"><Edit /></el-icon>
            </div>
            <div class="menu-empty" v-if="menuList.length===0">暂无分类，请先添加</div>
          </el-scrollbar>
          <el-button @click="showAddImgMenu" type="primary" style="width: 100%;" size="small">新增分类</el-button>
        </div>
      </el-col>
      <el-col :span="19" v-loading="loading">
        <div class="img-box">
          <div class="add-img-btn"><UpFile listType="text" accept=".jpg,.png,.jpeg,.webp,.gif" @uploadSuccessImgAdmin="uploadSuccessImgAdmin" isClearFiles multiple></UpFile></div>
          <div class="img-list">
            <div class="img-item" v-for="(item,index) in list" :key="index"  style="width: 100px; height: 100px">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="item.url"
                  :preview-teleported="true"
                  fit="contain"
              />
              <div @click="selectImg(index)" class="img-select-icon" title="选择">
                <div v-if="showSelect" class="select-icon"><el-icon v-if="item.checked" size="12" color="#409eff"><Select /></el-icon></div>
              </div>
              <div class="img-item-icon">
                <el-icon @click="showImgView(index)" color="#fff" size="14" title="放大" style="cursor: pointer;" ><ZoomIn /></el-icon>
                <el-icon @click="deleteImg(item)" color="#f65276" size="14" title="删除" style="cursor: pointer;" ><Delete /></el-icon>
              </div>
            </div>
          </div>
        </div>
        <div v-if="list.length===0" class="img-empty">当前分类图片为空~</div>
        <pagination
            class="img-pagination"
            layout="prev, pager, next"
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.size"
            @pagination="getList"
            small
            :pager-count="4"
        />
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
        <el-button type="primary" @click="selectImgRes">确认选择</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      title="分类管理"
      v-model="menuOpen"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input  v-model="form.name"  maxLength="6" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="展示排序" prop="sort">
        <el-input-number  v-model="form.sort" v-number="{value:3,call:(val)=>form.sort=val}" placeholder="请输入展示排序" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer" v-loading="loadingMenu">
        <el-button @click="menuOpen = false" size="small">关 闭</el-button>
        <el-button @click="delImgMenuApi" v-if="form.id" type="danger" size="small">删除</el-button>
        <el-button type="primary" @click="onsubmitMenu" size="small">{{ form.id?"修改":"新增" }}</el-button>
      </div>
    </template>
  </el-dialog>
  <el-image-viewer  :initial-index="initialIndex" @close="() => { showViewer = false }" v-if="showViewer" :url-list="urlList" />
</template>

<script setup>
  // import {getImgMenu,addImgMenu,delImgMenu,upImgMenu,getImgAdmin,addImgAdmin,delImgAdmin} from "@/api/components";
  import {addImgMenu,getImgMenu,upImgMenu,delImgMenu,getImgAdmin,addImgAdmin,delImgAdmin} from "@/api/components";
  import UpFile from '@/components/upFile/index.vue';
  const props=defineProps({
    //接收字符串："url,url,url"    数组：[{url:""},{url:""}]或者["url","url"]
    modelValue: [String, Array],
    //modelValue返回和接收格式，string 返回"url,url,url" ；arrayStr 返回["url","url"] ； arrayObj 返回[{url:""},{url:""}]
    runType:{
      type:String,
      default:"arrayObj"
    },
    //区分模块 商城：1；点单：2
    channel:{
      type:Number,
      default:1
    },
    //选择图片的数量 为0不限制
    selectNum:{
      type:Number,
      default:0
    },
    //图片的属性名称
    itemName:{
      type:String,
      default:"url"
    }
  })
  const {proxy}=getCurrentInstance();
  const emit=defineEmits();
  const open = ref(false);
  const menuOpen = ref(false);
  const menuIndex=ref(0);
  //用来判断如果编辑的是已经选中的，隐藏删除按钮
  const menuEditIndex=ref(0);
  const menuId=ref(0);
  const menuList=ref([]);
  const loading = ref(false);
  const loadingMenu = ref(false);
  const showViewer = ref(false)
  const initialIndex=ref(0);
  const urlList = ref([]);
  const list=ref([]);
  //外部已经存有的图片数量
  const existNum = ref(0);
  const data = reactive({
    form: {},
    queryParams: {
      page: 1,
      size: 15
    },
    total: 0,
    rules: {
      name: [
        { required: true, message: "分类名称不能为空", trigger: "blur" }
      ]
    }
  });
  const {queryParams, total, form, rules} = toRefs(data);
  watch(() => props.modelValue, val => {
    if (val) {
      const arr = Array.isArray(val) ? val : props.modelValue.split(",");
      existNum.value = arr.length;
    } else {
      return existNum.value=0;
    }
  },{ deep: true, immediate: true });
  //如果只需要选择一张
  const showSelect = computed(() => {
    return props.selectNum === 0 || props.selectNum-existNum.value>1;
  });
  async function getImgMenuApi(){
    try {
      loadingMenu.value=true;
      const {data}=await getImgMenu({channel:props.channel});
      menuList.value=data;
      return data;
    }finally {
      loadingMenu.value=false;
    }
  }
  async function getList(){
    try {
      loading.value=true;
      const res=await getImgAdmin({...queryParams.value,menuId:menuId.value,channel:props.channel});
      list.value=res.data;
      total.value=res.total;
      urlList.value=res.data.map(t=>t.url);
    }finally {
      loading.value=false;
    }
  }
  function showAddImgMenu(){
    menuOpen.value=true;
    form.value={sort:0}
  }
  async function onsubmitMenu(){
    await proxy.$refs['formRef'].validate();
    try {
      loadingMenu.value=true;
      const {id}=form.value;
      id&&await upImgMenu({...form.value,channel:props.channel});
      !id&&await addImgMenu({...form.value,channel:props.channel});
      proxy.$modal.msgSuccess(id?"修改成功":"新增成功！")
      menuOpen.value=false;
      await getImgMenuApi();
      filterMenuIndex()
    }finally {
      loadingMenu.value=false;
    }
  }
  function menuItemEvent(row,index){
    menuIndex.value=index;
    menuId.value=row.id;
    getList();
  }
  function showMenuEdit(row,index){
    form.value={...row};
    menuEditIndex.value=index;
    menuOpen.value=true;
  }
  async function delImgMenuApi(){
    await proxy.$modal.confirm(`确认删除分类：${form.value.name||''} ？`)
    try {
      loadingMenu.value=true;
      await delImgMenu(form.value);
      proxy.$modal.msgSuccess("删除成功！");
      menuOpen.value=false;
      await getImgMenuApi();
      //如果删除的是选中的,默认选中第一个
      if(menuEditIndex.value==menuIndex.value){
        menuEditIndex.value=menuIndex.value=0;
        menuId.value=menuList.value[0].id;
        getList();
      }else filterMenuIndex()
    }finally {
      loadingMenu.value=false;
    }
  }
  //选择跟随
  function filterMenuIndex(){
    const res=menuList.value.findIndex(item=>item.id==menuId.value);
    if(res!=-1){
      menuEditIndex.value=menuIndex.value=res
    }else {
      menuEditIndex.value=menuId.value=0;
      menuId.value=menuList.value[0].id;
      getList();
    }
  }
  async function uploadSuccessImgAdmin(fileList){
    try {
      loading.value=true;
      await addImgAdmin({imgArr:fileList.map(t=>({...t,menuId:menuId.value,channel:props.channel}))});
      getList();
    }finally {
      loading.value=false;
    }
  }
  function showImgView(index){
    initialIndex.value=index;
    showViewer.value = true;
  }
  async function deleteImg(item){
    await proxy.$modal.confirm(`如果此图片已经被引用，删除后将会全部失效。请确认是否删除？`,"删除提示");
    try {
      loading.value=true;
      await delImgAdmin({id:item.id});
      getList();
      proxy.$modal.msgSuccess("删除成功！");
    }finally {
      loading.value=false;
    }
  }
  function selectImg(index){
    const res=list.value.filter(t=>t.checked);
    if(props.selectNum!=0)if(res.length>=(props.selectNum-existNum.value)&&!list.value[index].checked) return proxy.$modal.msgError(`一次性最多选择${props.selectNum-existNum.value}张图片`);
    list.value[index].checked=!list.value[index].checked;
    //只需要一张直接默认确认选择
    if(!showSelect.value) selectImgRes();
  }
  function selectImgRes(){
    const res=list.value.filter(t=>t.checked);
    if(res.length==0) return proxy.$modal.msgError("请选择图片");
    emit("update:modelValue", listToString(res));
    emit("imgAdminRes", listToString(res));
    open.value=false;
  }
  // 对象转成指定字符串分隔
  function listToString(list) {
    switch (props.runType) {
      case "string":
        return list.map(t=>t[props.itemName]).join(',');
        break;
      case "arrayStr":
        return list.map(t=>t[props.itemName]);
        break;
      case "arrayObj":
        return list;
        break;
      default :
        return ""
    }
  }
  function showOpen(){
    getImgMenuApi().then((data)=>{
      if(data.length>0) menuId.value=data[menuIndex.value].id;
      getList();
    })
    open.value=true;
  }
  defineExpose({showOpen})

</script>

<style lang="scss" scoped>
  .menu-box{
    text-align: center;
    padding: 0 10px;
    border-right: 2px dashed #dedede;
    .menu-title{
      font-weight: 700;
      font-size: 16px;
      margin-left: -10px;
    }
    .menu-empty{
      font-size: 12px;
      margin-top: 100px;
      text-align: center;
    }
    .menu-item{
      position: relative;
      padding: 10px;
      border-top: 1px solid #e5e5e5;
      cursor: pointer;
      .menu-name{
        font-size: 12px;
        margin-left: -10px;
      }
      .menu-icon{
        position: absolute;
        top: 2px;
        right: 8px;
      }
    }
    .menu-active{
      font-weight: 700;
      color: #409eff;
      background: #ecf5ff;
    }
  }
  .img-empty{
    color: #999;
    text-align: center;
    margin-top: 100px;
  }
  .img-box{
    position: relative;
    .add-img-btn{
      text-align: right;
      position: absolute;
      top: -70px;
      right: 0px;
      z-index: 9;
    }
    :deep(.el-upload-list){
      background: #f1f1f1;
      border-radius: 3px;
    }
    .img-list{
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .img-item{
        margin-left: 10px;
        margin-bottom: 10px;
        position: relative;
        box-shadow: 0 0 2px 1px #e0e0e0;
        overflow: hidden;
        border-radius: 2px;
        &:last-child{
          margin-right: 0;
        }
        .img-item-icon{
          position: absolute;
          width: 100%;
          height: 25px;
          left: 0;
          bottom: 0;
          z-index: 9;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 10px;
          background: rgb(0 0 0 / 50%);
        }
        .img-select-icon{
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          cursor: pointer;
          .select-icon{
            position: absolute;
            top: 0;
            right: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 15px;
            height: 15px;
            border: 1.5px solid #409eff;
            border-radius: 2px;
          }
        }
      }
    }
  }
  .img-pagination{
    position: absolute;
    bottom: -20px;
    right: 0px;
    transform: scale(0.8);
  }
</style>
